import { login, getInfo } from "@/api/user";
import { getToken, setToken, removeToken ,saveUserNamePass } from "@/utils/auth";
import { resetRouter, anyRoute, asyncRoutes, constantRoutes } from "@/router";
import router from "@/router";
import cloneDeep from "lodash/cloneDeep";

const getDefaultState = () => {
  return {
    id: "",
    token: getToken(),
    username: "",
    routes: [],
    resultAsyncRoutes: [],
    resultAllAsyncRoutes: [],
    realName: "",
    roles: "",
  };
};

const state = getDefaultState();

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState());
  },
  SET_TOKEN: (state, token) => {
    state.token = token;
  },
  SET_USERINFO: (state, userInfo) => {
    state.id = userInfo.id;
    state.username = userInfo.username;
    state.realName = userInfo.realName;
    state.roles = userInfo.roles;
    state.routes = userInfo.routes;
  },
  SET_ROUTES: (state, asyncRoutes) => {
    state.resultAsyncRoutes = asyncRoutes;
    //计算出当前用户需要展示所有路由
    state.resultAllAsyncRoutes = constantRoutes.concat(
      state.resultAsyncRoutes,
      anyRoute
    );
    //给路由器添加新的路由
    router.addRoutes(state.resultAllAsyncRoutes);
    console.log(state.resultAllAsyncRoutes);
  },
};

const filterRoutes = (asyncRoutes, routes) => {
  return asyncRoutes.filter((item) => {
    if (routes.includes(item.name)) {
      if (item.children && item.children.length != 0) {
        item.children = filterRoutes(item.children, routes);
      }
      return true;
    }
  });
};

const actions = {
  // user login
  async login({ commit }, userInfo) {
    const { username, password } = userInfo;
    const res = await login({ username: username.trim(), password: password });
    if (res.code === 200) {
      commit("SET_TOKEN", res.data);
      setToken(res.data);
      saveUserNamePass(userInfo)
      return "ok";
    } else {
      return Promise.reject(new Error("请求失败"));
    }
  },

  async getInfo({ commit, state }) {
    const res = await getInfo(state.token);
    if (res.code == 401) {
      return
    }
    commit("SET_USERINFO", res.data);
    commit("SET_ROUTES", filterRoutes(cloneDeep(asyncRoutes), res.data.routes));
    return res.data;
  },

  // user logout
  logout({ commit, state }) {
    removeToken(); // must remove  token  first
    resetRouter();
    commit("RESET_STATE");
  },

  // remove token
  resetToken({ commit }) {
    return new Promise((resolve) => {
      removeToken(); // must remove  token  first
      commit("RESET_STATE");
      resolve();
    });
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
